// pages/orderCenter/mgyOrder/index.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "蘑菇乐园预约", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    road: '您了解到蘑菇乐园的途径',
    roadList: [{
        id: 0,
        name: '朋友介绍'
      }, {
        id: 1,
        name: '抖音'
      },
      {
        id: 2,
        name: '公众号'
      }
    ],
    qy: '选择您所在的区域',
    qyList: [{
        city_id: '1',
        city_name: '渝中区'
      },
      {
        city_id: '2',
        city_name: '大渡口区'
      },
      {
        city_id: '3',
        city_name: '江北区'
      },
      {
        city_id: '4',
        city_name: '沙坪坝区'
      },
      {
        city_id: '5',
        city_name: '九龙坡区'
      },
      {
        city_id: '6',
        city_name: '南岸区'
      },
      {
        city_id: '7',
        city_name: '北碚区'
      },
      {
        city_id: '8',
        city_name: '渝北区'
      },
      {
        city_id: '9',
        city_name: '巴南区'
      },
      {
        city_id: '10',
        city_name: '万州区'
      },
      {
        city_id: '11',
        city_name: '涪陵区'
      },
      {
        city_id: '12',
        city_name: '綦江区'
      },
      {
        city_id: '13',
        city_name: '大足区'
      },
      {
        city_id: '14',
        city_name: '黔江区'
      },
      {
        city_id: '15',
        city_name: '长寿区'
      },
      {
        city_id: '16',
        city_name: '江津区'
      },
      {
        city_id: '17',
        city_name: '合川区'
      },
      {
        city_id: '18',
        city_name: '永川区'
      },
      {
        city_id: '19',
        city_name: '南川区'
      },
      {
        city_id: '20',
        city_name: '璧山区'
      },
      {
        city_id: '21',
        city_name: '铜梁区'
      },
      {
        city_id: '22',
        city_name: '潼南区'
      },
      {
        city_id: '23',
        city_name: '荣昌区'
      },
      {
        city_id: '24',
        city_name: '开州区'
      },
      {
        city_id: '25',
        city_name: '梁平区'
      },
      {
        city_id: '26',
        city_name: '武隆区'
      }
    ],
    bmNum: 0, //报名人数
    dateList: [],
    chooseDate: -1, //日期选择
    sjdArr: [{
        id: 0,
        img: 'images/orderCenter/am.png',
        isBlack: 0
      },
      {
        id: 1,
        img: 'images/orderCenter/pm.png',
        isBlack: 0
      }
    ],
    chooseTime: -1,
    showMonment: true, //是否显示须知

    openid: '',
    shareTitle: '',
    shareImg: '',
    is_register: 0,
    tipsContent: '',
    list: [],
    pageIndex: 1,
    flag: 0,
    btnText: '前往支付',
    money: 0,
    totalMoney: 0,
    successUrl: ''
  },


  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  //点击我知晓了
  closeMonment() {
    let that = this;
    that.setData({
      showMonment: false
    })
  },
  //选择日期
  chooseDate(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;

    var list = that.data.dateList;
    if (list[id]['status'] == '暂停预约') {
      app.showTip('抱歉,您选择的时间已经暂停预约了哦,请选择其他时间预约');
      return;
    } else if (list[id]['status'] == '预约已满') {
      app.showTip('抱歉,您选择的时间预约人数已满了哦,请选择其他时间预约');
      return;
    }

    //更改选择的时间状态
    that.setData({
      chooseDate: id
    });


    wx.showLoading({
      title: '时间段状态切换中...'
    })
    //后台请求时段是否满了
    wx.request({
      url: that.data.baseUrl + 'checkSjcIsBmLy.php',
      method: 'POST',
      data: {
        bm_time: list[id].ymd,
        page: that.data.pageIndex
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          //蘑菇乐园
          if (res.data.sjdArr[0].is_black == 1) {
            //上午预约已满了
            that.setData({
              ['sjdArr[0].isBlack']: 1
            })
            if (that.data.chooseTime == 0) {
              that.setData({
                chooseTime: -1
              })
            }
          } else {
            //上午预约未满
            that.setData({
              ['sjdArr[0].isBlack']: 0
            })
            if (that.data.chooseTime == 0) {
              that.setData({
                chooseTime: -1
              })
            }
          }

          if (res.data.sjdArr[1].is_black == 1) {
            //下午预约已满了
            that.setData({
              ['sjdArr[1].isBlack']: 1
            })

            if (that.data.chooseTime == 1) {
              that.setData({
                chooseTime: -1
              })
            }
          } else {
            //下午预约未
            that.setData({
              ['sjdArr[1].isBlack']: 0
            })

            if (that.data.chooseTime == 1) {
              that.setData({
                chooseTime: -1
              })
            }
          }
        }
        wx.hideLoading();
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  //时段选择
  chooseTime(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    //判断是否预约已满了
    if (that.data.sjdArr[id].isBlack == 1) {
      return;
    }
    that.setData({
      chooseTime: id
    })
  },
  add() {
    let that = this;
    let bmNum = that.data.bmNum;
    let price = that.data.money;
    if (bmNum < 5) {
      bmNum++;
    }

    that.setData({
      bmNum,
      totalMoney: that.gshNum(price) * bmNum
    })
  },
  reduce() {
    let that = this;
    let bmNum = that.data.bmNum;
    let price = that.data.money;
    if (bmNum > 0) {
      bmNum--;
      that.setData({
        bmNum,
        totalMoney: that.gshNum(price) * bmNum
      })
    }

  },
  //选择了解途径
  roadChange(e) {
    let that = this;
    that.setData({
      road: that.data.roadList[e.detail.value].name,
    })
  },
  //选择您所在的区域
  qyChange(e) {
    let that = this;
    that.setData({
      qy: that.data.qyList[e.detail.value].city_name,
    })
  },
  // 关闭弹窗
  onConfimClose() {
    var that = this;
    wx.redirectTo({
      url: that.data.successUrl
    });
  },
  //预约
  order() {
    let that = this;

    //判断是否注册过了
    if (that.data.is_register == 0) {
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/orderCenter/mgyOrder/index');
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/select-login/select-login'
              })
            }
          }
        }
      })
      return;
    }

    if (that.data.flag == 1) {
      return;
    }
    let bmNum = that.data.bmNum;
    let chooseDate = that.data.chooseDate;
    let chooseTime = that.data.chooseTime;
    let road = that.data.road;
    let qy = that.data.qy;

    if (bmNum == 0) {
      app.showTip("请确定报名人数");
      return;
    }
    if (chooseDate == -1) {
      app.showTip("请选择日期");
      return;
    }
    if (chooseTime == -1) {
      app.showTip("请选择时段");
      return;
    }
    if (road == '您了解到蘑菇乐园的途径') {
      app.showTip("请选择了解到蘑菇乐园的途径");
      return;
    }
    if (qy == '选择您所在的区域') {
      app.showTip("请选择您所在的区域");
      return;
    }

    //提交数据
    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });
      wx.showLoading({
        title: '数据提交中...',
        mask: true
      });
      wx.request({
        url: that.data.baseUrl + 'addMglyBm.php',
        method: 'POST',
        data: {
          openid: that.data.openid,
          createtime: that.data.dateList[that.data.chooseDate].ymd,
          bmPeople: bmNum,
          yy_time: that.data.chooseTime,
          road: road,
          region: qy,
          amount: that.data.totalMoney
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();

          if (res.data.status == 1) {
            //后台请求成功
            //判断是否需要支付费用
            if (res.data.is_header_succ == 0) {
              wx.redirectTo({
                url: '/pages/orderCenter/mgyOrder/detail?id=' + res.data.id
              })
            } else {
              //不需要支付费用
              that.selectComponent('#confirmTtips').openPop();
              that.setData({
                successUrl: '/pages/activityCenter/paySuccess?payTime=' + res.data.payTime + "&payMoney=0&payOrderNumber=" +
                  res.data.payOrderNumber
              });
            }
          } else {
            app.showTip(res.data.msg)
          }
          that.setData({
            flag: 0
          });
        },
        fail: function (res) {
          wx.hideLoading();
          that.setData({
            flag: 0
          });
          app.showTip('当前报名人数过多,请稍候重试');
        }
      });
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');
    console.log(that.data.bmNum)

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getMglyOrderPageInfo(res.data.openid);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getMglyOrderPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getMglyOrderPageInfo(openid) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getMglyOrderPageInfo.php',
      method: 'POST',
      data: {
        openid: openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            is_register: res.data.is_register,
            tipsContent: res.data.tipsContent,
            dateList: res.data.list,
            money: res.data.price
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo_order.php',
      method: 'POST',
      data: {
        pid: 5
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },
  gshNum(num) {
    if (!isNaN(num) && parseInt(num, 10) === parseFloat(num)) {
      //为整型
      return parseInt(num);
    } else {
      //为浮点型 保留两位小数
      return parseFloat(parseFloat(num).toFixed(2));
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/orderCenter/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})